from rest_framework import serializers
from .models import Repository, History
from django_celery_results.models import TaskResult


class RepoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Repository
        fields = '__all__'
        read_only_fields = ['created_time']


class HistorySerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True, source="get_status_display")

    class Meta:
        model = History
        fields = '__all__'


class TaskResultRelatedByIdSerializer(serializers.ModelSerializer):
    class Meta:
        model = TaskResult
        fields = '__all__'

    def to_representation(self, instance):
        # instance = TaskResult.objects.get(task_id=instance)
        model = getattr(self.Meta, 'model')
        instance = model.objects.get(task_id=instance)
        return super().to_representation(instance)


class HistoryDetailSerializer(serializers.ModelSerializer):
    status = serializers.CharField(read_only=True, source="get_status_display")
    repo = RepoSerializer(read_only=True)
    executor_name = serializers.CharField(read_only=True, source="executor.username")
    task_result = TaskResultRelatedByIdSerializer(read_only=True, source='task_id')

    class Meta:
        model = History
        fields = '__all__'
